package handlers

import (
	"animal-hub/models"
	"animal-hub/pkg"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Login(c *gin.Context) {

	username := c.Query("username")
	password := c.Query("password")
	var login models.User
	er := models.DB.Where("username = ?", username).First(&login).Error
	if er != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if pkg.Md5str(password) != login.Password {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	details := c.PostForm("details")
	if title == "" || content == "" || details == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	add := models.Life{
		Title:   title,
		Content: content,
		Details: details,
	}
	err := models.DB.Create(&add).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var count int64
	models.DB.Model(&models.Life{}).Count(&count)

	var list []models.Life
	err := models.DB.Offset(offset).Limit(size).Find(&list).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"count": count,
		"list":  list,
	})
	return
}
